<?php
namespace Core\Service;

use Phalcon\Di\Injectable;
use Phalcon\Db\Profiler as DatabaseProfiler;
use Phalcon\Mvc\Model\Manager as ModelsManager;
use Phalcon\Mvc\Model\Transaction\Manager as TransactionManager;

class Database extends Injectable {

    protected $_connection;

    public function register() {
        $config = (array)$this->config->database;
        $adapter = '\Phalcon\Db\Adapter\Pdo\\' . ucfirst($config['adapter']);
        unset($config['adapter']);
        $this->_connection = new $adapter($config);
        $this->_profiler();
        $this->di->setShared('db', $this->_connection);
        $this->di->setShared(
            'modelsManager',
            function () {
                $modelsManager = new ModelsManager();
                return $modelsManager;
            }
        );

        $this->di->setShared(
            'transactions',
            function () {
                return new TransactionManager();
            }
        );
        return $this;
    }

    protected function _profiler() {
        $config = $this->config->system;
        $isProfiler = $config->profiler;
        $isDebug = $config->debug;
        if($isProfiler || $isDebug) {
            // Attach logger & profiler.
            $logger = null;
            $profiler = null;

            if ($isDebug && $this->di->has('logger')) {
                $logger = $this->di->get("logger", array("db"));
            }
            if ($isProfiler) {
                $profiler = new DatabaseProfiler();
            }
            $this->eventsManager->attach(
                'db',
                function ($event, $connection) use ($logger, $profiler) {
                    if ($event->getType() == 'beforeQuery') {
                        $statement = $connection->getSQLStatement();
                        if ($logger) {
                            $logger->info($statement);
                        }
                        if ($profiler) {
                            $profiler->startProfile($statement);
                        }
                    }
                    if ($event->getType() == 'afterQuery') {
                        // Stop the active profile.
                        if ($profiler) {
                            $profiler->stopProfile();
                        }
                    }
                }
            );

            if ($profiler && $this->di->has('profiler')) {
                $this->di->get('profiler')->setDbProfiler($profiler);
            }
            $this->_connection->setEventsManager($this->eventsManager);
        }
        return $this;
    }
}
